import axios from "axios";

import { SHA256, enc } from "crypto-js";
import  {WordsKeys} from './transform'
/**
 * 文本翻译工具
 * @param q 翻译文本
 * @param from 翻译目标语言
 * @param appId appid
 * @param key 密钥
 * @returns {Promise}
 */
export default async function translate(
  q: WordsKeys,
  to: string,
  config: { appId: string; key: string; language: string }
) {
  let { appId, key, language } = config;
  //当前语言和翻译语言相通直接返回翻译语言文本
  if (language == to) {
    return Promise.resolve(q)
  }
  try {
    let salt = new Date().getTime();
    let curtime = Math.round(new Date().getTime() / 1000);
    let words=q.map(item=>item.value);
    let input = calculateInput(words.join(''));
    const params: any = {
      q:words,
      from: "auto",
      to,
      appKey: appId,
      salt,
      sign: SHA256(appId + input + salt + curtime + key).toString(),
      signType: "v3",
      curtime,
    };

    // let req:any=await axios.get('https://openapi.youdao.com/v2/api',params)

    let url =
      "https://openapi.youdao.com/v2/api?" +
      params.q.map((a: string) => "q=" + a).join("&");
    params.q = null;
    let req: any = await axios({
      url,
      method: "get",
      params,
      transformResponse(data: any) {
        try {
            data = JSON.parse(data);
            data.translateResults=data.translateResults.map((item,index)=>(
              {
                value:item.translation,
                name:q[index].name
              }
            ));
            return data;
        } catch (error) {
          throw Error('响应翻译数据解析失败')
        }
      },
    });

    if (req.data && req.data.errorCode != 0) {
      throw req;
    }
    return req.data.translateResults;
  } catch (error) {
    if (error.response && error.response.status === 0)
      throw Error("网络未连接无法发送反义请求");
    else throw error;
  }
}

function calculateInput(q: string): string {
  var len = q.length;
  if (len <= 20) return q;
  return q.substring(0, 10) + len + q.substring(len - 10, len);
}

// translate('中国足球','en','71d2507bee5602cc','YtbuFSsu7EtzlvyOUpXgmf2FX9g5cQgI').then(res=>{
//   console.log('res',res)
// }).catch(err=>{
//   console.log('翻译错误',err)
// })
